import axios from 'axios'
import { setCookie, getCookie } from '@/utils/cookie'
import router from '@/router';

const request = axios.create({
	// 云服务器
	baseURL: 'https://service-h966xj6o-1317003402.gz.apigw.tencentcs.com/release/',

	// 本地服务器
	// baseURL: 'http://localhost:3000/',
	timeout: 5000
})

axios.defaults.withCredentials = true;
// 请求拦截器
request.interceptors.request.use(
	(config) => {
		// config.url += '?realIP=116.25.146.177'
		// 如果有cookie
		if (getCookie('loginCookie')) {
			const cookie = getCookie('loginCookie')
			if (config.url?.lastIndexOf('?') === -1) config.url += `?cookie=${cookie}`
			else config.url += `&cookie=${cookie}`
		}
		// 给请求地址加上时间戳
		const time = new Date().getTime()
			if (config.url?.lastIndexOf('addtime') === -1) {
				if (config.url?.lastIndexOf('?') === -1) config.url += `?timestamp=${time}`
				else config.url += `&timestamp=${time}`
			}
		return config
	}, (error) => { })

// 响应拦截器
request.interceptors.response.use(
	(response) => {
		if (response.data.cookie) {
			setCookie('loginCookie', response.data.cookie, '1')
		}
		if (response.data.code === 302) {
			window.$message.error('登录已过期,请重新登录')
			router.push({ name: 'login' })
		}
		return response.data
	}, (error) => { })

export default request